package com.fjwt.gz.task.offfline;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.entity.ActivityEntity;
import com.fjwt.gz.service.impl.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;

/**
 * 活动过期下线
 */
@Slf4j
@Component
public class ActivityOffLineTask {


    @Autowired
    private ActivityService activityService;
    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

//    @Scheduled(cron = "${cron.ActivityOffLineTask}")//每3秒执行一次
    @Transactional
    public void start() {
        log.info("开始进入活动过期定时任务，下线已过期的活动，开始时间:{}", DateUtil.now());

        //查询条件： 状态4上线
        LambdaQueryWrapper<ActivityEntity> gw = ActivityEntity.gw();
        gw.notIn(ActivityEntity::getState, Constants.ACTIVITY_STATE.DRAFT, Constants.ACTIVITY_STATE.EXPIRED);
        gw.lt(ActivityEntity::getEndTime, new Date());

        ArrayList<ActivityEntity> updateList = new ArrayList<>();
        int currentPageIndex = 1; //当前页码
        while (true) {
            try {
                IPage<ActivityEntity> activityEntityIPage = activityService.page(new Page(currentPageIndex, QUERY_PAGE_SIZE), gw);
                log.info("查询页数：{}，size:{}，结果list：{}", currentPageIndex, QUERY_PAGE_SIZE, JSONUtil.toJsonStr(activityEntityIPage));

                if (activityEntityIPage == null || activityEntityIPage.getRecords().isEmpty()) { //本次查询无结果, 不再继续查询;
                    break;
                }

                for (ActivityEntity activityEntity : activityEntityIPage.getRecords()) {
                    log.info("此时进行处理的信息的是：{}", JSONUtil.toJsonStr(activityEntity));
                    activityEntity.setState(Constants.ACTIVITY_STATE.EXPIRED);
                    activityEntity.setUpdatedAt(new Date());
                    updateList.add(activityEntity);
                    currentPageIndex++;
                }
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }
        }
        // 执行批量更新
        if (ObjectUtils.isNotEmpty(updateList)) {
            activityService.updateBatchById(updateList);
        }

        log.info("结束活动过期定时任务，下线已过期的活动，结束时间:{}", DateUtil.now());
    }
}
